// pages/shop/shop-search/shop-search.js
var httpUtil = require('../../../utils/httpUtil.js');
var uiUtil = require('../../../utils/uiUtil.js');
var util = require('../../../utils/util.js');
var WXBizDataCrypt = require('../../../utils/cryptoUtil.js');
const appId = 'wx2e65f1eb244a839b';
const app = getApp();
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mchHome: null, //商家信息
    shopCartLists: [],//购物车列表
    shopCartView: false, //展开购物车

    greensLists: {
      totalCount: null,
      pageCount: null,
      pageNo: "0",
      pageSize: "30",
      dataList: []
    },
    requestGoodsTask: null, //请求task
    isLoadingMore: false,
    enableLoadMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    let mchHome = JSON.parse(options.mchHome);
    let shopCartLists = JSON.parse(options.shopCartLists);
    that.setData({
      pages: app.globalData.pages,
      authorizeFlag: app.globalData.authorizeFlag,
      mchHome: mchHome,
      shopCartLists: shopCartLists
    });
  },

  /**
   * 展开购物车
   */
  shopCartViewChange() {
    if (that.data.shopCartLists.length > 0) {
      that.setData({
        shopCartView: !that.data.shopCartView
      })
    }
  },
  /**
   * 购物车查询
   */
  getShopCart(mchId) {
    httpUtil.PostRequest("searchCart", {
      mchId: mchId
    }, {
        success(res) {
          if (res.length == 0) {
            that.setData({
              shopCartView: false
            })
          }
          that.setData({
            shopCartLists: res
          })
          that.shopCartChange(res);
          uiUtil.hideLoading();
        },
        fail(code, res) {
          uiUtil.showToast(res)
        },
        complete() { }
      })
  },

  /**
   * 更改商家首页购物车
   */
  shopCartChange:function(res){
    var pages = getCurrentPages();
    var lastPage = pages[pages.length - 2];
    if (lastPage.route == "pages/shop/shop/shop") {
      lastPage.setData({
        shopCartLists: res
      })
    }
  },

  /**
   * 拨打商家电话
   */
  mchPhone: function (e) {
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },


  /**
   * 购物车保存
   */
  getSaveCart(e) {
    let item = e.currentTarget.dataset.item;
    let mchId = that.data.mchHome.mchId;
    let mchName = that.data.mchHome.mchName; 
    let productcount = e.currentTarget.dataset.productcount;
    let type = e.currentTarget.dataset.type;
    productcount = parseInt(productcount) + parseInt(type);

    httpUtil.PostRequest("saveCart", {
      mchId: mchId,
      mchName: mchName,
      productId: item.productId||item.id,
      productName: item.name || item.productName,
      productImgUrl: item.imageUrl || item.productImgUrl,
      productCount: productcount,
      price: item.price,
      amount: item.price * productcount
    }, {
        success(res) {
          that.getShopCart(mchId);
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  }, 

  /**
   * 购物车删除
   */
  getDelCart(e) {
    let productId =e.id|| e.currentTarget.dataset.productid;
    let cartId = that.data.shopCartLists[0].id;
    let mchId = that.data.mchHome.mchId;

    httpUtil.PostRequest("delCart", {
      cartId: cartId,
      productId: productId
    }, {
      success(res) {
        that.getShopCart(mchId);
      },
      fail(code, res) {
        uiUtil.showToast(res);
      },
      complete() { }
    })
  }, 


  /**
   * 商家菜品查询
   */
  searchMchProduct: function (res){
    let productName = res.detail.value.productName||res;
    if(res.detail.value.productName){
      that.setData({
        "greensLists.pageNo":"0"
      })
    }
    var pageNo = parseInt(that.data.greensLists.pageNo)+1;
    let pageSize = that.data.greensLists.pageSize;
    let dataList = that.data.greensLists.dataList;
    let mchId = that.data.mchHome.mchId;

    that.setData({
      productName:productName
    })

    var lastRequestTask = that.data.requestGoodsTask;
    if (lastRequestTask) {
      try {
        lastRequestTask.abort()
      } catch (e) { }
    }

    var curPage = that.data.greensLists.pageNo;
    if (curPage != 0 && (!that.data.enableLoadMore || that.data.isLoadingMore)) { //不可加载||正在加载\
      return;
    }
    
    var requestTask =httpUtil.PostRequest("searchMchProduct", {
      mchId: mchId,
      productName: productName,
      pageNo: pageNo,
      pageSize: pageSize
    }, {
      success(res) {
        if (0 == that.data.greensLists.pageNo) {
          res.dataList = res.dataList || [];
        } else {
          res.dataList = dataList.concat(res.dataList || []);
        }
        that.setData({
          greensLists: res,
          enableLoadMore: res.dataList.length < res.totalCount
        })
        if(res.totalCount==0){
          uiUtil.showToast("抱歉，没有符合条件的商品");
          that.setData({
            "greensLists.pageNo":"0"
          })
        }
      },
      fail(code, res) {
        that.setData({
          enableLoadMore: false
        })
        if (0 == that.data.greensLists.pageNo) { //内容为空
          that.setData({
            fail: true
          })
        } else {
          uiUtil.showToast(res);
        }
      },
      complete() {
        that.setData({
          isLoadingMore: false
        })
      }
    })
    that.setData({
      requestGoodsTask: requestTask
    })
  },

  /**
  * 触底加载
  */
  onReachBottom(){
    that.searchMchProduct(that.data.productName);
  },

  /**
   * 点击去结算，获取用户信息
   */
  getuserinfo(e){
    if(e.detail.errMsg=="getUserInfo:fail auth deny"){ //用户拒绝授权获取用户信息
      return
    }

    let mchhome=e.currentTarget.dataset.mchhome;
    let shopcartlists=e.currentTarget.dataset.shopcartlists;

    var sessionKey = app.globalData.sessionKey;
    var encryptedData = e.detail.encryptedData;
    var iv =  e.detail.iv;
    var pc = new WXBizDataCrypt(appId, sessionKey)
    var data = pc.decryptData(encryptedData , iv)
    app.globalData.userInfo=data;

    wx.navigateTo({
      url:"/pages/index/order/order-pre/order-pre?mchHome="+mchhome+"&shopCartLists="+shopcartlists
    })
  }
})